import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../widget/mq_text.dart';
import '../../widget/mq_button.dart';
import '../../services/screen_adapter.dart';
import '../../config/config.dart';

class RegisterFirst extends StatefulWidget {
  RegisterFirst({Key key}) : super(key: key);

  @override
  _RegisterFirstState createState() => _RegisterFirstState();
}

class _RegisterFirstState extends State<RegisterFirst> {

  String tel = "";

  sendCode() async{
    RegExp reg = new RegExp(r'^1\d{10}$');
    if(reg.hasMatch(tel)) {
      var api = '${Config.domain}api/sendCode';
      var response = await Dio().post(api, data: {'tel': tel});
      if(response.data['success']) {
        print(response); // 服务器返回的验证码
        Navigator.pushNamed(context, '/registerSecond', arguments: {
          'tel': tel
        });
      } else {
        Fluttertoast.showToast(
          msg: "${response.data['message']}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.grey[600],
          textColor: Colors.white,
          fontSize: 16.0
        );
      }
    } else {
      Fluttertoast.showToast(
        msg: "手机号格式不对",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.grey[600],
        textColor: Colors.white,
        fontSize: 16.0
      );
    }
  }

  @override
  Widget build(BuildContext context) {

    ScreenAdapter.init();

    return Scaffold(
      appBar: AppBar(
        title: Text('用户注册-第一步')
      ),
      body: Container(
        padding: EdgeInsets.all(ScreenAdapter.width(20)),
        child: ListView(
          children: <Widget>[
            SizedBox(height: 50),
            MqText(
              text: '请输入手机号',
              onChange: (value) {
                setState(() => tel = value);
              },
            ),
            SizedBox(height: 20),
            MqButton(
                text: '下一步',
                color: Colors.red,
                height: 74,
                callback: sendCode,
              )
          ]
        )
      )
    );
  }
}
